package com.mt.mall.service.good.impl;

import com.mt.mall.dao.good.SpecificationDao;

import com.mt.common.core.exception.BusinessException;
import com.mt.common.core.web.base.PageDTO;
import com.mt.common.core.web.base.PageResultDTO;
import com.mt.common.core.web.base.BaseEntity;
import com.mt.common.core.web.BaseService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.mt.mall.entity.good.Specification;
import com.mt.mall.service.good.SpecificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class SpecificationServiceBean extends BaseService implements SpecificationService {

    private static Logger logger = LogManager.getLogger();

	@Autowired
	private SpecificationDao specificationDao;

	@Resource
	private RedisTemplate<String, List<Specification>> redisTemplate;

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 根据分页参数查询商品销售规格集合
	 *
	 * @param pageDTO 分页条件
	 */
	@Override
	public PageResultDTO findSpecifications(PageDTO pageDTO){
        pageDTO.setStartIndex((pageDTO.getCurrentPage()-1)*pageDTO.getPageSize());
		//TODO:请在此校验参数的合法性
		this.validateFindSpecifications(pageDTO);
		if(this.getStoreId()!=-1){
			pageDTO.getFilters().put("shopId",this.getStoreId());
			pageDTO.getFilterTypes().put("shopId","单值");
		}
		List<Specification> specificationDTOS = this.specificationDao.findSpecifications(pageDTO);
		Long totalCount = this.specificationDao.findSpecificationTotalCount(pageDTO);

		PageResultDTO pageResultDTO = new PageResultDTO();
		pageResultDTO.setTotalCount(totalCount);
		pageResultDTO.setDatas(specificationDTOS);

		return pageResultDTO;
	}

	/**
	 * 查询全部商品销售规格集合
	 *
	 */
	@Override
	public List<Specification> findAllSpecifications(){
		List<Specification> allSpecifications = this.specificationDao.findAllSpecifications(this.getStoreId());
		return streamMethod(allSpecifications);
	}

	/**
	 * stream方法转换成树形结构
	 * @param specificationList
	 * @return
	 */
	public List<Specification> streamMethod(List<Specification> specificationList) {
		List<Specification> list = specificationList.stream()
				// 筛选出父节点
				.filter(t -> t.getParentId() == null)
				// 设置父节点的子节点列表
				.map(item -> {item.setChildren(streamGetChildren(item, specificationList)); return item;})
				.collect(Collectors.toList());
		return list;
	}
	/**
	 * stream 方式递归查找子节点列表
	 * @return
	 */
	public List<Specification> streamGetChildren(Specification specification, List<Specification> specificationList) {
		List<Specification> list = specificationList.stream()
				.filter(t -> t.getParentId()!=null&&t.getParentId().equals(specification.getEid()))
				.map(item -> {item.setChildren(streamGetChildren(item, specificationList)); return item;})
				.collect(Collectors.toList());
		return list;
	}

	/**
	 * 查询所有商品销售规格集合(只提取ID 和 Name)
	 *
	 */
	@Override
	public List<Specification> findAllSpecificationsWithIdName(){
		//TODO:请在此校验参数的合法性
		this.validateFindAllSpecificationsWithIdName();
		return this.specificationDao.findAllSpecificationsWithIdName();
	}

	/**
	 * 根据名称查询商品销售规格集合(只提取ID 和 Name)
	 *
	 * @param specificationName 名称
	 */
	@Override
	public List<Specification> findSpecificationsWithIdNameByName(String specificationName){
		//TODO:请在此校验参数的合法性
		this.validateFindSpecificationsWithIdNameByName(specificationName);
		//TODO:缓存取对应参数
		Set<String> keys = stringRedisTemplate.keys("searchData:Specification_where_specificationName_" + specificationName);
		List<Specification> specifications = new ArrayList<>();
		if (keys.isEmpty()) {
		specifications = this.specificationDao.findSpecificationsWithIdNameByName(specificationName);
		redisTemplate.opsForValue().set("searchData:Specification_where_specificationName_" + specificationName, specifications, 30, TimeUnit.DAYS);
		} else {
		specifications = redisTemplate.opsForValue().get("searchData:Specification_where_specificationName_" + specificationName);
		}
		return specifications;
	}

	/**
	 * 根据ID查询指定的商品销售规格(只提取ID 和 Name)
	 *
	 * @param specificationId Id
	 */
	@Override
	public Specification findSpecificationsWithIdNameById(Long specificationId){
		//TODO:请在此校验参数的合法性
		this.validateFindSpecificationsWithIdNameById(specificationId);
		return this.specificationDao.findSpecificationsWithIdNameById(specificationId);
	}

	/**
	 * 根据ID查询指定的商品销售规格
	 *
	 * @param specificationId Id
	 */
	@Override
	public Specification findSpecification(Long specificationId){
		//TODO:请在此校验参数的合法性
		this.validateFindSpecification(specificationId);
		return this.specificationDao.findSpecification(specificationId);
	}

	/**
	 * 根据ID查询指定的商品销售规格(包含外键)
	 *
	 * @param specificationId Id
	 */
	@Override
	public Specification findSpecificationWithForeignName(Long specificationId){
		//TODO:请在此校验参数的合法性
		this.validateFindSpecificationWithForeignName(specificationId);
		return this.specificationDao.findSpecificationWithForeignName(specificationId);
	}

	/**
	 * 新增商品销售规格
	 *
	 * @param specification 实体对象
	 */
	@Override
	public Specification saveSpecification(Specification specification){
		//TODO:请在此校验参数的合法性
		this.validateSaveSpecification(specification);
		//TODO:填充公共参数
		this.setSavePulicColumns(specification);
		specification.setShopId(this.getStoreId());
		Long rows = this.specificationDao.saveSpecification(specification);
		if(rows != 1)
		{
			String error = "新增保存商品销售规格出错，数据库应该返回1,但返回了 "+rows;
			throw new BusinessException(error);
		}
		return specification;
	}

	/**
	 * 更新商品销售规格
	 *
	 * @param specification 实体对象
	 */
	@Override
	public Specification updateSpecification(Specification specification){
		//TODO:请在此校验参数的合法性
		this.validateUpdateSpecification(specification);
		Long rows = this.specificationDao.updateSpecification(specification);
		if(rows != 1)
		{
			String error = "修改保存商品销售规格出错，数据库应该返回1,但返回了 "+rows+",数据可能被删除";
			throw new BusinessException(error);
		}
		return specification;
	}

	/**
	 * 根据ID删除商品销售规格
	 *
	 * @param specificationId ID
	 */
	@Override
	public void deleteSpecification(Long specificationId){
		//TODO:请在此校验参数的合法性
		this.validateDeleteSpecification(specificationId);

		Map<Class<? extends BaseEntity>,EntityUsage> entityUsageMap = this.checkForeignEntity(Specification.class, specificationId);
		if(entityUsageMap != null && entityUsageMap.size() >0){
			StringBuilder errors = new StringBuilder();
			errors.append("计划删除的数据正在被以下数引用\n");
			for(EntityUsage entityUsage : entityUsageMap.values()){
				errors.append("\t").append(entityUsage.getEntityLabel()).append("\n");
				for(Map.Entry<Long,String> entry : entityUsage.getUsageIdNames().entrySet() ){
					errors.append("\t\t").append(entry.getKey()).append("\t").append(entry.getValue()).append("\n");
				}
			}
			errors.append("，不能删除，请检查处理后再删除");
			throw  new BusinessException(errors.toString());
		}

		Long rows = this.specificationDao.deleteSpecification(specificationId);
		if(rows != 1){
			String error = "删除商品销售规格出错，数据可能已经被删除";
			throw new BusinessException(error);
		}
	}

	@Override
	public List<Specification> findSpecificationsByCommodityId(Long commodityId) {
		List<Specification> specificationList=this.specificationDao.findSpecificationsByCommodityId(commodityId);
		return streamMethod(specificationList);
	}
	//TODO:---------------验证-------------------

	private void validateFindSpecifications(PageDTO pageDTO) {
	//TODO:请使用下面方法添加数据过滤条件
	//		pageDTO.addFilter("creatorId",this.getLoginUserId());
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateFindSpecificationsWithIdNameByName(String specificationName) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}


	private void validateFindAllSpecificationsWithIdName() {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateFindSpecificationsWithIdNameById(Long specificationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateFindSpecification(Long specificationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateFindSpecificationWithForeignName(Long specificationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateSaveSpecification(Specification specification) {
	//不为空判断
	if (specification.getEid() != null || specification.getCreatorId() != null || specification.getCreateDatetime() != null) {
	throw new BusinessException("非法请求");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateUpdateSpecification(Specification specification) {
	//不为空判断
	if (specification.getEid() == null) {
	throw new BusinessException("唯一标识不能为空");
	}
	//是否存在判断
	if (this.specificationDao.findSpecificationTotalCount(PageDTO.create(Specification.FIELD_ID, specification.getEid())) == 0) {
	throw new BusinessException("修改的商品销售规格 " + specification.getName() + " 不存在，修改失败，请重试或联系管理员");
	}
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	private void validateDeleteSpecification(Long specificationId) {
	//TODO:请完善数据校验规则和数据权限判断，如果有问题请抛出异常，参看下面validateUpdateSpecification()写法
	}

	@Override
	public boolean canDownloadAttachment(String formName, Long id) {
	return true;
	}
}
